package cn.tradewin.advisor.persist.services.impl;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import cn.tradewin.advisor.persist.mapper.CustomerMapper;
import cn.tradewin.advisor.persist.model.CodeLabel;
import cn.tradewin.advisor.persist.model.Customer;
import cn.tradewin.advisor.persist.services.CustomerService;

public class CustomerServiceImpl implements CustomerService {

	
	private final SqlSessionFactory sqlSessionFactory;
	
	public CustomerServiceImpl(SqlSessionFactory sqlSessionFactory) {
		this.sqlSessionFactory = sqlSessionFactory;
	}
	
	
	@Override
	public List<Customer> listAllCustomers() {
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			CustomerMapper mapper = session.getMapper(CustomerMapper.class);
			return mapper.getAllCustomers();
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}

	@Override
	public int addCustomer(Customer customer) {
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			CustomerMapper mapper = session.getMapper(CustomerMapper.class);
			int iCount = mapper.insert(customer);
			if (iCount < 0) {
				session.rollback();
				return iCount;
			}
			session.commit();
			return  iCount;
		} catch (Exception e) {
			if (session != null) {
				session.rollback();
			}
			throw new RuntimeException(e.getMessage());
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}


	@Override
	public List<CodeLabel> getAllCustomerOptions() {
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			CustomerMapper mapper = session.getMapper(CustomerMapper.class);
			return mapper.getAllCustomerOptions();
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}
}